﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.SqlServerCe;

namespace KelionesLapaiV2
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private SqlCeConnection conn = null;
        public MainWindow()
        {
            InitializeComponent();
            conn = new SqlCeConnection("data source='Data.sdf';");
            conn.Open();
            Calendar.SelectedDate = DateTime.Now;
        }
        ~MainWindow()
        {
            conn.Close();
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            saveData(Calendar.SelectedDate.GetValueOrDefault());
        }

        private bool saveData(DateTime date)
        {
            Data data = new Data();
            data.Date = date;
            data.KmStart = Convert.ToInt32(km_Start.Text);
            data.KmEnd = Convert.ToInt32(km_End.Text == string.Empty ? "0" : km_End.Text);
            data.KmDriven = Convert.ToInt32(km_Driven.Text);

            data.LtEnd = Convert.ToInt32(lt_End.Text);
            data.LtFilled = Convert.ToInt32(lt_Filled.Text);
            data.LtStart = Convert.ToInt32(lt_Start.Text);
            data.LtUsed = Convert.ToInt32(lt_Used.Text);
            data.NotWorked = NotWorked.IsChecked.GetValueOrDefault(false);
            return DataHelper.InsertUpdateData(conn, data);
        }

        private void Calendar_SelectedDatesChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cbAutoSave.IsChecked != null && (bool)cbAutoSave.IsChecked)
                saveData(Convert.ToDateTime(e.RemovedItems[0]));

            resetFields(true);

            if (!readFields(true))
            {
                DateTime date = Calendar.SelectedDate.Value;
                date = date.AddDays(-1);
                Data data = DataHelper.SelectData(conn, date);
                while (data != null && data.NotWorked && data.KmStart != 0)
                {
                    date = date.AddDays(-1);
                    data = DataHelper.SelectData(conn, date);
                }
                if (data != null)
                {
                    km_Start.Text = data.KmEnd.ToString();
                    lt_Start.Text = data.LtEnd.ToString();
                }
            }
        }

        private void resetFields(bool forceAll)
        {
            km_Driven.Text = "0";
            km_End.Text = "0";
            km_Start.Text = "0";

            lt_End.Text = "0";
            lt_Filled.Text = "0";
            lt_Start.Text = "0";
            lt_Used.Text = "0";
            if(forceAll)
                NotWorked.IsChecked = false;
        }

        private void toggleFields(bool enabled)
        {
            if (!enabled)
            {
                km_Driven.IsEnabled = false;
                km_End.IsEnabled = false;
                km_Start.IsEnabled = false;

                lt_End.IsEnabled = false;
                lt_Filled.IsEnabled = false;
                lt_Start.IsEnabled = false;
                lt_Used.IsEnabled = false;
            }
            else
            {
                km_Driven.IsEnabled = true;
                km_End.IsEnabled = true;
                km_Start.IsEnabled = true;

                lt_End.IsEnabled = true;
                lt_Filled.IsEnabled = true;
                lt_Start.IsEnabled = true;
                lt_Used.IsEnabled = true;
            }
        }

        private bool readFields(bool force)
        {
            Data data = null;
            if (Calendar.SelectedDate != null)
                data = DataHelper.SelectData(conn, Convert.ToDateTime(Calendar.SelectedDate));
            if (data != null)
            {
                if (!data.NotWorked)
                {
                    if (data.KmStart == 0)
                        return false;
                    km_Driven.Text = data.KmDriven.ToString();
                    km_End.Text = data.KmEnd.ToString();
                    km_Start.Text = data.KmStart.ToString();

                    lt_End.Text = data.LtEnd.ToString();
                    lt_Filled.Text = data.LtFilled.ToString();
                    lt_Start.Text = data.LtStart.ToString();
                    lt_Used.Text = data.LtUsed.ToString();
                }
                else if (force)
                {
                    resetFields(false);
                    NotWorked.IsChecked = true;
                }
            }

            return data != null;
        }

        private void NotWorked_Checked(object sender, RoutedEventArgs e)
        {
            toggleFields(false);
        }

        private void NotWorked_Unchecked(object sender, RoutedEventArgs e)
        {
            readFields(false);
            toggleFields(true);
        }

        private void km_End_LostFocus(object sender, RoutedEventArgs e)
        {
            km_Driven.Text = (Convert.ToInt32(km_End.Text) - Convert.ToInt32(km_Start.Text)).ToString();
            double used = Convert.ToInt32(km_Driven.Text)*(Convert.ToDouble(const_param1.Text)/100);
            if (used % 1 >= 0.4)
                used = Math.Ceiling(used);
            else
                used = Math.Floor(used);

            lt_Used.Text = used.ToString();
            lt_End.Text =
                (Convert.ToInt32(lt_Start.Text) - Convert.ToInt32(lt_Used.Text) + Convert.ToInt32(lt_Filled.Text)).ToString();
        }

        private void lt_Filled_LostFocus(object sender, RoutedEventArgs e)
        {
            lt_End.Text =
                (Convert.ToInt32(lt_Start.Text) - Convert.ToInt32(lt_Used.Text) + Convert.ToInt32(lt_Filled.Text)).ToString();
        }

        private void btnRecalc_Click(object sender, RoutedEventArgs e)
        {
            List<Data> list = new List<Data>();
            Data temp = null;
            DateTime selectedDate = Calendar.SelectedDate.GetValueOrDefault();
            DateTime start =  new DateTime(selectedDate.Year, selectedDate.Month, 1);
            DateTime end = start.AddMonths(1);
            while (start != end)
            {
                temp = DataHelper.SelectData(conn, start);
                if (temp != null)
                {
                    list.Add(temp);
                }
                start = start.AddDays(1);
            }

            if (list.Count > 1)
            {
                int DrivenMonth = list[list.Count-1].KmEnd - list[0].KmStart;
                int FilledMonth = 0;
                int UsedMonth = 0;
                foreach (var data in list)
                {
                    if (!data.NotWorked)
                    {
                        FilledMonth += data.LtFilled;
                        UsedMonth += data.LtUsed;
                    }
                }

                lblDrivenMonth.Content = DrivenMonth.ToString();
                lblFilledMonth.Content = FilledMonth.ToString();
                lblUsedMonth.Content = UsedMonth.ToString();
            }
        }

        private void km_End_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                lt_Filled.Focus();
                if (lt_Filled.Text == "0")
                    lt_Filled.SelectAll();
            }
            else if (e.Key == Key.Escape)
            {
                NotWorked.IsChecked = true;
                Calendar.SelectedDate = Calendar.SelectedDate.Value.AddDays(1);
                if (km_End.Text == "0")
                    km_End.SelectAll();
            }
        }

        private void lt_Filled_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                km_End.Focus();
                Calendar.SelectedDate = Calendar.SelectedDate.Value.AddDays(1);
                if (km_End.Text == "0")
                    km_End.SelectAll();
            }
        }
    }
}
